<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="css/index.css">
    <script src="js/jquery.min.js"></script>
    <script>
        //当整个页面加载完毕之后
        $(document).ready(function () {
            let url = "WS://localhost:8080/woniuchat/";
            //指向websocket对象
            let ws = null;

            //给join按钮添加点击事件
            $("#join").click(function () {
                //获取昵称
                //判空
                let userName = $("#userName").val();
                //建立连接
                //如果连接成功WS非空
                ws = new WebSocket(url + userName);

                //绑带事件 回调函数
                ws.onopen = function () {
                    console.log("连接服务器成功")
                }
                //当服务器接收到消息触发事件
                ws.onmessage = function (result) {
                    var textarea = document.getElementById('textarea');
                    textarea.append(result.data + "\n");
                    //将文本域的滚动条滚动到最后
                    textarea.scrollTop = textarea.scrollHeight;
                    console.log(result)
                }
                //当断开连接时触发
                ws.onclose = function () {
                    console.log("离开了聊天室")
                }
            });

            //离开聊天室按钮
            $("#out").click(function () {
                if (ws != null) {
                    ws.close();
                }
            });
            //发送消息
            $("#send").click(function () {
                //获得输入的消息
                let message = $("#message").val();
                //发消息
                ws.send(message);
                //清空输入框消息
                $("#message").val("");
            })
        });
    </script>
</head>
<body>
<div id="box">
    <p>蜗牛聊天室</p>
    <textarea rows="10" cols="50" disabled="disabled" id="textarea"></textarea><br>
    <div class="infoBox">
        用户名:<input type="text" id="userName"><br><br>
        <button style="color: green;" id="join">加入聊天室</button>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <button style="color: red;" id="out">离开聊天室</button>
    </div>
    <br><br>
    <div class="infoBox">
        消&nbsp;&nbsp;&nbsp;息:<input type="text" id="message"><br><br>
        <button id="send">发送消息</button>
    </div>
    <br>
</div>
</body>
</html>